#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE  64

int main(int argc,char *argv[])
{  
#if 0
    /*argc是命令行参数的个数*/
    printf("argc = %d\n",argc);
    for(int i = 0;i < argc;i++)
    {
        printf("argv[%d] = %s\n",i,argv[i]);
    }
#endif
    if(argc != 3)
    {
        printf("param num is invaild.\n");
        exit(-1);
    }

    const char * srcFile = argv[1];


    int dstMode = 0;
    /* 判断源文件是否具备写权限 */
    int ret = access(srcFile,W_OK);
    if(ret != -1)
    {
        printf("srcFile write permission.\n");
        dstMode |= W_OK;
    }
    /* 判断源文件是否具备读权限 */
    ret = access(srcFile,R_OK);
    if(ret != -1)
    {
        printf("srcFile read permission.\n");
        dstMode |= R_OK;
    }
    /* 判断源文件是否具备执行权限 */
    ret = access(srcFile,X_OK);
    if(ret != -1)
    {
        printf("srcFile execute permission.\n");
        dstMode |= X_OK;
    }
    const char * dstFile = argv[2];
    /* 判断文件是否存在 */
    ret = access(srcFile,F_OK);
    if(ret == -1)
    {
        printf("src file open error\n");
        exit(-1);
    }
    int srcFd = open(srcFile,O_RDONLY);
    if(srcFd == -1)
    {
        printf("src file open error\n");
        exit(-1);
    }
    /* 程序走到这个地方:意味着原文件存在 */

    /* 十进制转八进制 */
    int dstFd = open(dstFile,O_WRONLY | O_CREAT,0771);
    if(dstFd == -1)
    {
        printf("dst file open error\n");
        exit(-1);
    }
    char buffer[BUFFER_SIZE] = {0};

    int readBytes = 0;
    while(1)
    {
        /* 读到的字节数 */
        readBytes = read(srcFd,buffer,BUFFER_SIZE - 1);
        if((readBytes < BUFFER_SIZE - 1) || (readBytes == 0))
        {
            write(dstFd,buffer,readBytes);
            break;
        }
        write(dstFd,buffer,readBytes);
        memset(buffer,0,BUFFER_SIZE);
    }
    /* 关闭文件 */
    close(srcFd);
    close(dstFd);
    
    return 0;
}